package com.cty.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Auther: cty
 * @Date: 2020/3/12 17:14
 * @Description:  控制器  作用域传值的四种方式
 * @version: 1.0
 */
@Controller
public class DemoController {
    // 1 使用原生Servlet
    @RequestMapping("demo1")
    public String demo(HttpServletRequest req){
        // request作用域
        req.setAttribute("req", "req的值");
        // session作用域
        HttpSession session = req.getSession();
        session.setAttribute("session", "session的值");
        // application作用域
        ServletContext application = req.getServletContext();
        application.setAttribute("application", "application的值");

        return "/index.jsp";
    }

    // 2 使用Map集合
    // 本质上是存储在request作用域
    @RequestMapping("demo2")
    public String demo2(Map<String, Object> map){
        map.put("map", "map的值");
        return "/index.jsp";
    }

    // 3 使用SpringMVC中的Model接口
    // 本质上是存储在request作用域
    @RequestMapping("demo3")
    public String demo3(Model model){
        model.addAttribute("model", "model的值");
        return "/index.jsp";
    }

    // 4 使用SpringMVC中的ModelAndView类
    // 本质上是存储在request作用域
    @RequestMapping("demo4")
    public ModelAndView demo4(){
        ModelAndView mav = new ModelAndView("/index.jsp");
        mav.addObject("mav", "mav的值");
        return mav;
    }

}
